﻿//负责 MES 数据模型和 HTTP 异步调用。


using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace ShangWeiDemo1
{
    /// <summary>
    /// 包含 MES 接口的调用逻辑和数据模型
    /// </summary>
    public class MesService
    {
        private readonly Action<string> _logAction;
        private readonly HttpClient _httpClient;

        // API接口响应数据模型
        private class ApiResponse
        {
            public int code { get; set; }
            public ApiData data { get; set; }
            public string msg { get; set; }
            public bool success { get; set; }
        }

        // API响应数据中的详细数据模型
        private class ApiData
        {
            public bool isComplete { get; set; }
            public string reason { get; set; }
            public string specs { get; set; }
            public string u9No { get; set; }
        }

        // 统一返回结果的结构体
        public struct MesResult
        {
            public bool Success { get; set; }       // 接口调用和解析是否成功
            public bool IsComplete { get; set; }    // 前工序是否完成
            public string U9No { get; set; }        // U9号
            public string Specs { get; set; }       // 零件号
            public string Reason { get; set; }      // 失败原因/错误信息
            public string RawJson { get; set; }     // 原始 JSON 字符串
        }


        public MesService(Action<string> logAction, HttpClient httpClient)
        {
            _logAction = logAction;
            _httpClient = httpClient;
        }

        private void WriteToLogFile(string msg) => _logAction?.Invoke(msg);

        /// <summary>
        /// 异步检查前工序状态的HTTP GET请求，并解析结果
        /// </summary>
        /// <param name="barcode">扫码结果 (启动码)</param>
        /// <returns>包含解析结果的 MesResult 结构体</returns>
        public async Task<MesResult> CheckPreviousProcessAndParseAsync(string barcode)
        {
            MesResult result = new MesResult
            {
                Success = false,
                IsComplete = false,
                U9No = "N/A",
                Specs = "N/A",
                Reason = "未知错误",
                RawJson = string.Empty
            };

            // ⚠️ 注意：这里假设 workStation 为 "5"，实际项目中应从配置文件中读取
            string workStation = "5";
            string baseUrl = "https://mes.jsxq.group/mes/api/v1/checkLines/checkLineResultByCockpitBom/{0}";
            string url;

            if (!string.IsNullOrEmpty(workStation))
            {
                url = string.Format(baseUrl + "?workStation={1}", barcode, workStation);
            }
            else
            {
                url = string.Format(baseUrl, barcode);
            }

            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode(); // 检查 HTTP 状态码

                string resultJson = await response.Content.ReadAsStringAsync();
                result.RawJson = resultJson; // 记录原始 JSON

                // 核心实现：将原始 JSON 字符串写入日志
                WriteToLogFile($"MES 接口返回原始 JSON: {resultJson}");

                // JSON 反序列化
                ApiResponse apiResponse = JsonConvert.DeserializeObject<ApiResponse>(resultJson);

                if (apiResponse != null && apiResponse.success && apiResponse.code == 200 && apiResponse.data != null)
                {
                    result.Success = true;
                    result.IsComplete = apiResponse.data.isComplete;
                    result.U9No = apiResponse.data.u9No ?? "N/A";
                    result.Specs = apiResponse.data.specs ?? "N/A";
                    result.Reason = apiResponse.data.reason;

                    string logMsg = result.IsComplete
                                ? $"前工序检查成功。"
                                : $"前工序检查未通过，原因: {result.Reason}";
                    WriteToLogFile(logMsg);
                }
                else
                {
                    // 接口返回非 200/success=false 等异常状态
                    result.Success = false;
                    result.Reason = apiResponse != null ? apiResponse.msg : "接口返回格式错误";
                    WriteToLogFile($"MES 接口返回非成功状态: {result.Reason}");
                }
            }
            catch (HttpRequestException httpEx)
            {
                result.Reason = $"网络/接口调用失败: {httpEx.Message}";
                WriteToLogFile(result.Reason);
            }
            catch (Exception ex)
            {
                result.Reason = $"内部处理错误: {ex.Message}";
                WriteToLogFile(result.Reason);
            }

            return result;
        }
    }
}